package cn.ywang.spring.demo.aspect;

import cn.ywang.spring.framework.aop.intercept.Joinpoint;

import java.util.Arrays;

/**
 * @author BeatificWang
 * @date 2019/5/4 23:13
 */
public class LogAspect {

	/**
	 * 在调用一个方法之前，执行before方法
	 *
	 * @param joinPoint
	 */
	public void before(Joinpoint joinPoint) {
		joinPoint.setUserAttribute("startTime_" + joinPoint.getMethod().getName(), System.currentTimeMillis());
		//这个方法中的逻辑，是由我们自己写的
		System.out.println("Invoker Before Method!!!" +
				                   "\nTargetObject:" + joinPoint.getThis() +
				                   "\nArgs:" + Arrays.toString(joinPoint.getArguments()));
	}

	/**
	 * 在调用一个方法之后，执行after方法
	 *
	 * @param joinPoint
	 */
	public void after(Joinpoint joinPoint) {
		System.out.println("Invoker After Method!!!" +
				                   "\nTargetObject:" + joinPoint.getThis() +
				                   "\nArgs:" + Arrays.toString(joinPoint.getArguments()));
		long startTime = (Long) joinPoint.getUserAttribute("startTime_" + joinPoint.getMethod().getName());
		long endTime = System.currentTimeMillis();
		System.out.println("use time :" + (endTime - startTime));
	}

	/**
	 * 在调用方法出现异常时，执行afterThrowing方法
	 *
	 * @param joinPoint
	 */
	public void afterThrowing(Joinpoint joinPoint, Throwable ex) {
		System.out.println("出现异常" +
				                   "\nTargetObject:" + joinPoint.getThis() +
				                   "\nArgs:" + Arrays.toString(joinPoint.getArguments()) +
				                   "\nThrows:" + ex.getMessage());
	}
}
